package net.lcheng.files.controller;

import com.alibaba.druid.util.StringUtils;
import net.lcheng.utils.DESUtils;
import net.lcheng.utils.UploadImgUtils;
import net.lcheng.utils.UploadResultModel;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.log4j.Logger;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.Random;

//import org.codehaus.jackson.map.ObjectMapper;

@RestController
public class UploadController {
    private static Logger log = Logger.getLogger(UploadController.class);

    @ResponseBody
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/img_upload", method = RequestMethod.POST)
    public UploadResultModel fileUpload(HttpServletRequest request, HttpServletResponse response, @RequestParam String img)
            throws ServletException, IOException, FileUploadException {
        UploadResultModel resultModel = new UploadResultModel();
        resultModel.setCode(-1);

        try {
            //访问服务器的sessionKey
            String key = "1b04c515b73755da703881d2b858261b";
            String userName = "zhaorenxue@123001";

            DESUtils des = new DESUtils(key);// 自定义密钥

            String userSessionKey = request.getParameter("textParams");
            log.info("Parameter-textParams:"+userSessionKey);
            log.info("Parameter-UserName:"+des.decrypt(userSessionKey));

            if(des.decrypt(userSessionKey).equals(userName)==false){
                //错误
                resultModel.setCode(-1);
                resultModel.setMsg("非法用户");
                return  resultModel;
            }

        }catch (Exception e){
            resultModel.setCode(-1);
            resultModel.setMsg("非法用户");
            return  resultModel;
        }


//        log.info("HEAD-textParams:"+request.getHeader("textParams"));

        log.info("开始上传");
        if (StringUtils.isEmpty(img)) {

            resultModel.setMsg("IMG IS NULL");
            //图像数据为空
            return resultModel;
        }

        ServletContext application = request.getSession().getServletContext();
        String savePath = application.getRealPath("/") + "attached/";

        // 文件保存目录URL
        String saveUrl = request.getContextPath() + "/attached/";

        String fileExt = "jpg";
        Properties properties = PropertiesLoaderUtils.loadAllProperties("config.properties");
        String imgDomain = properties.getProperty("imgDomain");


        log.info("创建文件夹");
        // 创建文件夹
        File saveDirFile = new File(savePath);
        if (!saveDirFile.exists()) {
            saveDirFile.mkdirs();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String ymd = sdf.format(new Date());
        savePath += ymd + "/";
        saveUrl += ymd + "/";
        File dirFile = new File(savePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }


        log.info("开始读取base64");

        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000);


        try {
            boolean returnResult = UploadImgUtils.base64ToImageOutput(img, savePath, newFileName,fileExt);
            if(returnResult){
                resultModel.setCode(0);
                resultModel.setUrl(imgDomain+saveUrl+newFileName+"."+fileExt);
            }else {
                resultModel.setMsg("生成图片失败");
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        return resultModel;
    }

}
